﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CardInChina.Bussiness.Frontend.Models;
using CardInChina.Data.Entity.Interface;
using CardInChina.Data.Entity.Entity;

namespace CardInChina.Bussiness.Frontend.Interface
{
    public class UserService
    {
        private CustomerService us = new CustomerService();
        private SysVerifyService svs = new SysVerifyService();
        private FavoriteService fs = new FavoriteService();
        private CardService cs = new CardService();

        public CustomerInfo ValidUserLogIn(UserLoginInfo logInfo)
        {
            if (logInfo == null) return null;
            var customer = us.Login(logInfo.userName, logInfo.pwd);
            if (customer == null) return null;
            CustomerInfo returnObj = BindCustomer(customer);
            return returnObj;
        }

        private CustomerInfo BindCustomer(Customer customer)
        {
            var cc = new CustomerInfo();
          
            cc.CustomerID = customer.CustomerID;
            cc.CustomerLogInName = customer.Account;
            cc.IsVIP = customer.IsVip ?? false;
            cc.Balance = customer.Balance;
            cc.PurchaseTimes = customer.PurchaseTimes;
            cc.IsActived = customer.IsActived;
            cc.Email = customer.Email;
            cc.Entity = customer;

            return cc;
        }

        public CustomerOrderInfoInUserWelcome GetCustomerOrderInfoInUserWelcomeByCustomerID(int customerID)
        {
            CustomerOrderInfoInUserWelcome customer = new CustomerOrderInfoInUserWelcome();
            Customer _customer = us.GetCustomerByCustomerID(customerID);

            customer.Account = _customer.Account;
            customer.AutoSend = _customer.AutoSend;
            customer.AvailableBonus = _customer.AvailableBonus;
            customer.Balance = _customer.Balance;
            customer.IsActived = _customer.IsActived;
            customer.IsVip = _customer.IsVip;
            customer.LastLogonDate = _customer.LastLogonDate;
            customer.PurchaseTimes = _customer.PurchaseTimes;

            customer.CanceledOrderCount = _customer.OfOrders.Count(o => o.PayStatus == 6);
            customer.PayedOrderCount = _customer.OfOrders.Count(o => o.PayStatus == 1 || o.PayStatus == 2);
            customer.NonPayedOrderCount = _customer.OfOrders.Count(o => o.PayStatus == 0);

            foreach (var order in _customer.OfOrders.OrderByDescending(order => order.LastModifiedTime).Take(4))
            {
                if (order != null && order.OfCard != null && order.OfCard.OfCardInfo != null)
                {
                    customer.LastestCards.Add(new LastCardInUserWelcome
                    {
                        CardName = order.OfCard.CardMemo,
                        Price = order.OfCard.Price,
                        VIPPrice = order.OfCard.VIPPrice,
                        CardInfoKey = order.OfCard.OfCardInfo.CardKey,
                        Photo = order.OfCard.Photo
                    });
                }

            }

            return customer;
        }

        public Customer GetCustomerBasicInfoByCustomerID(int customerID)
        {
            Customer _customer = us.GetCustomerByCustomerID(customerID);
            return _customer;
        }

        public FavoriteOperationResult AddFavoriteForCustomer(int customerID, int cardID)
        {
            if (GetCustomerBasicInfoByCustomerID(customerID) == null) return FavoriteOperationResult.Failed;
            if (cs.GetCardEntityByCardID(cardID) == null) return FavoriteOperationResult.Failed;
            if (fs.GetFavoriteByCustomerIDAndCardID(customerID, cardID) != null) return FavoriteOperationResult.Duplicate;
            fs.AddFavorite(customerID, cardID);
            return FavoriteOperationResult.Success;
        }

        public FavoriteOperationResult DeleteFavorite(int favoriteID, int customerID, int cardID)
        {
            Favorite f = fs.GetFavoriteByCustomerIDAndCardID(customerID, cardID);
            if (f == null) return FavoriteOperationResult.Failed;
            if (f.FavoriteID != favoriteID) return FavoriteOperationResult.Illegal;
            try
            {
                fs.DeleteFavorite(favoriteID);
                return FavoriteOperationResult.Success;
            }
            catch
            {
                return FavoriteOperationResult.Failed;
            }

        }

        public CustomerFavoriteInfoInUserWelcome GetCustomerFavoriteInfoInUserWelcomeByCustomerID(int customerID)
        {
            var favorites = fs.GetFavoritesByCustomerID(customerID);
            CustomerFavoriteInfoInUserWelcome cfuw = new CustomerFavoriteInfoInUserWelcome();
            foreach (var f in favorites)
            {
                if (!f.OfCard.OnSale) continue;
                if (f.OfCard.OfCardInfo == null) continue;
                if (!f.OfCard.OfCardInfo.OnSale) continue;
                cfuw.Favorites.Add(new FavoriteCardInfo
                {
                    CardID = f.OfCard.CardID,
                    CardName = f.OfCard.CardMemo + " " + CardInfo.ConvertGoodType(f.OfCard.GoodsType) + " - " + f.OfCard.Miane,
                    CardInfoKey = f.OfCard.OfCardInfo.CardKey,
                    CardInfoName = f.OfCard.OfCardInfo.CardName,
                    Photo = f.OfCard.Photo,
                    Price = f.OfCard.Price,
                    CreateTime = f.CreateDate,
                    VIPPrice = f.OfCard.VIPPrice,
                    CardKey = f.OfCard.CardKey,
                    FavoriteID = f.FavoriteID
                });
            }
            return cfuw;

        }

        /// <summary>
        /// Check if cid is a valid customer or not
        /// </summary>
        public bool ValidateRecommended(string cid)
        {
            int result;
            if (int.TryParse(cid, out result))
            {
                var customer = GetCustomerBasicInfoByCustomerID(result);
                return customer != null;
            }
            else
            {
                return false;
            }
        }


        public CustomerInfo Login(string account, string password)
        {
            var customer = us.Login(account, password);
           
            if (customer == null)
                return null;
            else
                return BindCustomer(customer);
        }


        public CustomerInfo Register(string email, string alias, string password, string referer, int? recommended, string ipAddress)
        {
            var customer = us.Register(email, alias, password, referer, recommended, ipAddress);
            return BindCustomer(customer);
        }


        public CustomerInfo VerifyEmail(string code)
        {
            // verify email
            var sv = svs.GetOne(code);
            if (sv == null)
                return null;

            // login
            var cid = sv.ForId;
            var customer = us.SetEmailVerified(cid);

            return BindCustomer(customer);
        }
    }
}
